package com.yzg.sign.project.service.impl;

import com.alibaba.fastjson.JSONObject;

import com.yzg.sign.project.common.BeanUtils;
import com.yzg.sign.project.common.HttpClientUtil;
import com.yzg.sign.project.common.Result;
import com.yzg.sign.project.common.TianCongUtils;
import com.yzg.sign.project.domain.Customer;
import com.yzg.sign.project.repository.CustomerRepository;
import com.yzg.sign.project.request.UpdateUserInfoRequest;
import com.yzg.sign.project.service.CustomerService;
import com.yzg.sign.project.token.TokenUtils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


import javax.transaction.Transactional;
import java.util.*;


@Service
@Transactional
public class CustomerServiceImpl implements CustomerService
{
    @Value("${weixin.appId}")
    private String appId;

    @Value("${weixin.appSecret}")
    private String appSecret;

    @Autowired
    private CustomerRepository customerRepository;

    @Autowired
    private TokenUtils tokenUtils;



    @Override
    public Result<Map<String,String>> code2Session(String code)
    {

        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code";
        url = url.replace("APPID",appId).replace("SECRET",appSecret).replace("JSCODE",code);
        JSONObject res = JSONObject.parseObject(HttpClientUtil.doGet(url));
        Optional<Customer> customer = customerRepository.findByOpenId(res.getString("openid"));
        Map<String,String> map = new HashMap<>();
        map.put("openId",res.getString("openid"));
        String token = null;
        if(customer.isPresent())
        {
            customer.get().setSessionKey(res.getString("session_key"));
            if(customer.get().getStatus()!=0)
            {
                token = tokenUtils.generateTokeCode(customer.get(),customer.get().getId());
            }
        }else{
            Customer customer1 = new Customer();
            customer1.setOpenId(res.getString("openid"));
            customer1.setSessionKey(res.getString("session_key"));
            System.out.println(TianCongUtils.register(res.getString("openid")));
            customerRepository.saveAndFlush(customer1);
        }
        map.put("token",token);
        return Result.<Map<String,String>>builder().success().data(map).build();
    }


    @Override
    public Result<String> updateUserInfo(UpdateUserInfoRequest request)
    {

        if(StringUtils.isNotEmpty(request.getOpenId()))
        {

            Optional<Customer> customer = customerRepository.findByOpenId(request.getOpenId());
            if(customer.isPresent())
            {
                Customer customer1 = customer.get();
                BeanUtils.copyProperties(request,customer1);
                customer1.setStatus(1);
                Customer result = customerRepository.saveAndFlush(customer1);
                tokenUtils.generateTokeCode(result,result.getId());

                return Result.<String>builder().success().data(tokenUtils.generateTokeCode(result,result.getId())).build();
            }
        }
        return Result.<String>builder().fail().message("openId 为空").build();
    }


}
